/**
 * @Description: 自动化注册组件 同步/异步
 * @author 刘贵
 * @date 2021/06/31
*/

import Vue from 'vue'

// 加载公共组件（异步组件 如果组件层文件夹名称没有.sync则异步加载，组件名为文件夹名称）
// 取三层目录下的目标为组件 /components/**/**/**.vue
let context = require.context('@/components/', true, /^\.\/[^/]+\/([^/.]+)(?!\.sync)\/([^/]+\.vue|component\.js|index\.js)$/i, 'lazy')
context.keys().map(fileName => {
  let componentName = fileName.replace(/.+\/([^/]+)\/[^/]+(\.vue|\.js)$/gi, '$1')
  Vue.component(componentName, () => context(fileName))
})

// 加载公共组件（同步组件 如果组件层文件夹名称有.sync则同步加载，组件名为去除.sync后的文件夹名称）
// 取三层目录下的目标为组件 /components/**/**.sync/**.vue
let contextSync = require.context('@/components/', true, /^\.\/[^/]+\/([^/]+)(\.sync)\/([^/]+\.vue|component\.js|index\.js)$/i)
contextSync.keys().map(fileName => {
  let componentName = fileName.replace(/.+\/([^/]+).sync\/[^/]+(\.vue|\.js)$/gi, '$1')
  const file = contextSync(fileName)
  Vue.component(componentName, file.default || file)
})

Vue.component('remote-js', {
  render (createElement) {
    return createElement('script', { attrs: { type: 'text/javascript', src: this.src } })
  },
  props: {
    src: { type: String }
  },
  watch: {
    src (v) {
      console.log(v)
    }
  }
})

Vue.component('uni-sdk', {
  render (createElement) {
    return createElement('div', { style: { display: 'none' } }, [
      createElement('remote-js', { props: { src: this.miniSDK } }),
      createElement('remote-js', { props: { src: 'https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js' } })
    ])
  },
  data () {
    return {
      miniSDK: ''
    }
  },
  created () {
    let url
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('AlipayClient') > -1) {
      // 支付宝小程序 JS-SDK
      url = 'https://appx/web-view.min.js'
    } else if (/QQ/i.test(userAgent) && /miniProgram/i.test(userAgent)) {
      // QQ 小程序 JS-SDK
      url = 'https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js'
    } else if (/miniProgram/i.test(userAgent)) {
      // 微信小程序 JS-SDK
      url = 'https://res.wx.qq.com/open/js/jweixin-1.4.0.js'
    } else if (/toutiaomicroapp/i.test(userAgent)) {
      // 字节跳动小程序 JS-SDK
      url = 'https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.1.js'
    } else if (/swan/i.test(userAgent)) {
      // 百度小程序 JS-SDK
      url = 'https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.18.js'
    }
    this.miniSDK = url
  }
})
